<?php
    verify();
    // 宽 高 验证字符个数 字符类型
    function verify($width=100, $height=50, $num=5, $codeType=2)
    {

        // 创建画布
        $image = imagecreatetruecolor($width, $height);
        // 填充颜色
        imagefill($image, 0, 0, lightColor($image));
        // 准备code
        switch($codeType){
            case 0: 
                $code = getNum($num);
                break;
            case 1: 
                $code = getChar($num);
                break;
            case 2: 
                $code = getNumChar($num);
                break;
            default:
                exit('类型错误');
        }
        // 绘制code
        for($i=0; $i<$num; $i++){
            $w = floor($width / $num);
            $x = mt_rand($w * $i + 5, ($i+1) * $w - 15);
            $y = mt_rand(10, $height-20);
            imagechar($image, 5, $x, $y, $code[$i], darkColor($image));
        }
        // 干扰元素
        for($i=0; $i<4; $i++){
            imagearc($image, mt_rand(0, $width), mt_rand(0, $height),mt_rand(80, $width), mt_rand(50, $height), 50, 160, darkColor($image));
        }
        for($i=0; $i<150; $i++){
            imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height),darkColor($image));
        }
        // 设置mime
        header('Content-type: image/png');
        // 生成图像
        imagepng($image);
        // 释放资源
        imagedestory($image);
    }
    // 浅色
    function lightColor($image)
    {
        return imagecolorallocate($image, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
    }
    // 深色
    function darkColor($image)
    {
        return imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
    }
    // 数字
    function getNum($num){
        $number = join('', range(0, 9));
        return substr(str_shuffle($number), 0, $num);
    } 
    // 字母
    function getChar($num){
        $char = join('', range('a', 'z'));
        $str = $char . strtoupper($char);
        return substr(str_shuffle($str), 0, $num);
    } 
    // 字母数字组合
    function getNumChar($num){
        $char = join('', range('a', 'z'));
        $number = join('', range(0, 9));
        $str = $char . strtoupper($char) . $number;
        return substr(str_shuffle($str), 0, $num);
    } 
